﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using MapControl.Bing.SoapClient.net.virtualearth.dev;
using GeoFramework;

namespace MapControl.Bing.SoapClient
{
    public class BingClientException : ApplicationException
    {
        public BingClientException(string msg)
            : base(msg)
        { }
    }

    public class BingClient
    {
        private GeocodeService geocodeService;

        public string ApiKey { get; set; }

        public BingClient(string apiKey)
        {
            ApiKey = apiKey;
            geocodeService = new GeocodeService();
        }

        public IEnumerable<Position> GetPositions(string query)
        {
            GeocodeRequest req = new GeocodeRequest();
            req.Credentials = GetCredentials();
            req.Query = query;
            GeocodeResponse response = geocodeService.Geocode(req);
            ValidResponse(response.ResponseSummary);
            List<Position> positions = new List<Position>();
            foreach (var item in response.Results)
            {
                foreach (var loc in item.Locations)
                {
                    positions.Add(new Position(new Latitude(loc.Latitude), new Longitude(loc.Longitude)));
                }
            }
            return positions;
        }

        private void ValidResponse(ResponseSummary responseSummary)
        {
            if (responseSummary.AuthenticationResultCode != AuthenticationResultCode.ValidCredentials)
                throw new BingClientException("Authentication failed:" + Environment.NewLine + responseSummary.AuthenticationResultCode.ToString() + Environment.NewLine + responseSummary.FaultReason);
            if (responseSummary.StatusCode != ResponseStatusCode.Success)
                throw new BingClientException("Request failed: " + Environment.NewLine + responseSummary.StatusCode.ToString() + Environment.NewLine + responseSummary.FaultReason);
        }

        private Credentials GetCredentials()
        {
            return new Credentials() { ApplicationId = ApiKey };
        }
    }
}
